package com.ehotting.edsta.mqbd.listener;

import com.alibaba.fastjson.JSON;
import com.ehotting.mqbd.api.bean.ConsumerNodeBean;
import com.ehotting.mqbd.core.helper.IPHelper;
import com.ehotting.mqbd.core.manager.ConsumerNodeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class ApplicationContextListener implements CommandLineRunner, DisposableBean {

    private static Logger logger = LoggerFactory.getLogger(ApplicationContextListener.class);

    @Autowired
    private IPHelper ipHelper;

    @Autowired
    private ConsumerNodeManager consumerNodeManager;

    private volatile boolean isRun = true;

    private Thread thread = null;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Start run.");
        Runnable run = new Runnable() {
            @Override
            public void run() {
                while (isRun){
                    logger.info("Set consumerNode info.");
                    ConsumerNodeBean consumerNode = new ConsumerNodeBean();
                    consumerNode.setIp(ipHelper.getIp());
                    consumerNode.setDate(new Date());
                    consumerNodeManager.save(consumerNode);
                    logger.info("Save consumerNode[{}].", JSON.toJSONString(consumerNode));
                    try {
                        Thread.sleep(30*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread = new Thread(run);
        thread.start();

        logger.info("Finish run.");
    }


    @Override
    public void destroy() throws Exception {
        logger.info("Start destroy.");
        interruptRegister();
        consumerNodeManager.delete(ipHelper.getIp());
        logger.info("Finish destroy.");
    }

    private void interruptRegister(){
        isRun = false;
        if(thread!=null){
            while(thread.isAlive() && !thread.isInterrupted() ){
                thread.interrupt();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}